<?php

namespace Admin\Validate;

use Application\Db;

class UserValidator extends \Zend_Validate_Abstract
{
    /** @var \Zend\Mvc\Router\RouteMatch $routeMatch */
    private $routeMatch;

    public function __construct($routeMatch = null)
    {
        $this->routeMatch = $routeMatch;
    }

    const MESSAGE = 'message';

    protected $_messageTemplates = array(
        self::MESSAGE => "User \"%value%\" already exists. Choose another user name and try again."
    );
    public function isValid($value)
    {
        $this->_setValue($value);
        $id = 0;
        if ($this->routeMatch && !($id = $this->routeMatch->getParam('id'))) {
            return false;
        }
        $db  = Db::getInstance();
        $select = $db->select();
        $select->from('user');
        $select->where('userName = ?', $value);
        if (($row = $db->fetchRow($select)) && $row['id'] != $id) {
            $this->_error(self::MESSAGE);
            return false;
        } else {
            return true;
        }
    }

}